<?php

namespace app\api\controller;

use app\services\CaptchaService;
use plugin\admin\app\model\User;
use support\Request;

class CaptchaController
{
    /**
     * 获取验证码
     * @return string
     */
    public function getCaptcha(Request $request)
    {
        try {
            $account = $request->post('account');
            $scenario = $request->post('scenario');

            if ($account == 'login' && get_user_id()) {
                if (get_current_language() == 'zh') {
                    $account = User::where('id', get_user_id())->value('mobile');
                } else {
                    $account = User::where('id', get_user_id())->value('email');
                }
            }

            echo $account;

            $captcha = CaptchaService::getCaptcha($account, $scenario);
            return ok_rsp('验证码获取成功', ['captcha' => $captcha]);
        } catch (\Exception $e) {
            echo $e->getMessage() . $e->getTraceAsString();
            return err_rsp($e->getMessage());
        }
    }

    /**
     * 校验验证码
     * @return string
     */
    public function validateCaptcha(Request $request)
    {
        try {
            $account = $request->post('account');
            $scenario = $request->post('scenario');
            $captcha = $request->post('captcha');

            if ($account == 'login' && get_user_id()) {
                if (get_current_language() == 'zh') {
                    $account = User::where('id', get_user_id())->value('mobile');
                } else {
                    $account = User::where('id', get_user_id())->value('email');
                }
            }

            $token = CaptchaService::validateCaptcha($account, $scenario, $captcha);
            return ok_rsp('验证码校验成功', ['token' => $token]);
        } catch (\Exception $e) {
            return err_rsp($e->getMessage());
        }
    }
}